package com.wh.codedemon.design.pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 *
 * @auther whoo7
 * @date 2024/1/1 21:26
 */
public class DynamicProxyHandler implements InvocationHandler {
    private Object target;

    public DynamicProxyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("执行代理方法前.....");
        Object result = method.invoke(target, args);
        System.out.println("执行代理方法后.....");
        return result;
    }

    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();
        DynamicProxyHandler dynamicProxyHandler = new DynamicProxyHandler(realSubject);
        Subject subject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), dynamicProxyHandler);
        subject.request();
    }
}
